package com.hht.baselibs.fragment

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.hht.baselibs.viewModel.BaseViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel


/**
 * Author:chen'hu
 * Time:2023/7/31 13:55
 * Description:This is BaseLibFragment
 */
abstract class BaseLibFragment<VM : BaseViewModel, DB : ViewDataBinding> : HhtBaseFragment(),
    CoroutineScope by MainScope() {
    protected lateinit var mContext: Context
    private var mRootView: View? = null
    protected lateinit var mViewModel: VM
    protected lateinit var mViewDataBind: DB

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = requireActivity()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        if (null == mRootView) {
            if (getLayoutResId() < 1) {
                throw NullPointerException("layout is not null ...")
            }
            mViewDataBind = DataBindingUtil.inflate(inflater, getLayoutResId(), container, false)
            //千万别用this，会出现生命周期不一样的情况
            // mViewDataBind.lifecycleOwner = viewLifecycleOwner
            mViewDataBind.lifecycleOwner = viewLifecycleOwner
            mRootView = mViewDataBind.root
        } else {
            (mRootView?.parent as ViewGroup).removeView(mRootView)
        }

        return mRootView
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initObserve()
    }

    override fun onDestroy() {
        super.onDestroy()
        //取消顶级父协程
        cancel()
    }

    protected abstract fun getLayoutResId(): Int

    protected abstract fun initView()

    protected abstract fun initObserve()
}